<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.main }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.item }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索框与添加按钮区 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入姓名、邮箱或手机号码" clearable v-model="queryInfo.condition" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList" />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table border :data="userList">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="telephone"> </el-table-column>
        <el-table-column label="角色" prop="role.roleName"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" @change="updateState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑用户信息" placement="top-start" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户信息" placement="top-start" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showDisDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="addForm.telephone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="editForm.telephone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <!-- destroy-on-close 每次关闭对话框都会摧毁内部所有的元素 -->
    <el-dialog title="分配权限" destroy-on-close :visible.sync="disDialogVisible" width="50%" @close="disDialogVisible = false" :close-on-click-modal="false">
      <!-- 显示当前角色基本信息 -->
      <div>
        <el-tag type="primary" effect="dark" class="tag">当前用户: {{ usr.username }}</el-tag>
        <el-tag type="info" effect="dark">当前角色: {{ role.roleName }}</el-tag>
      </div>
      <!-- 分配权限区 -->
      <el-table style="width: 100%" :data="rolesList" height="250" ref="disTable" border stripe @current-change="selected">
        <template>
          <el-table-column prop="id" width="40px">
            <template slot-scope="scope">
              <el-radio v-model="roleId" :label="scope.row">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="keyword" label="角色关键字"> </el-table-column>
          <el-table-column prop="description" label="角色描述"></el-table-column>
        </template>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="disDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="distribution">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      return regEmail.test(value) ? cb() : cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|17[6|7|8]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      return regMobile.test(value) ? cb() : cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 面包屑导航标题
      menuTitle: {
        main: '',
        item: ''
      },
      // 查询条件
      queryInfo: {
        condition: '',
        currentPage: 1,
        pageSize: 5
      },
      // 用户列表
      userList: [],
      // 总数
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户表单
      addForm: {
        username: '',
        email: '',
        telephone: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户信息表单
      editForm: {},
      // 编辑用户信息表单的验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑用户信息对话框的显示与隐藏
      editDialogVisible: false,
      // 角色 id
      roleId: '',
      // 控制分配角色对话框的显示与隐藏
      disDialogVisible: false,
      // 角色列表
      rolesList: [],
      // 用户
      usr: {},
      // 角色
      role: {}
    }
  },
  created() {
    this.getUserList()
    this.getMenuList()
  },
  methods: {
    // 获取面包屑导航标题
    async getMenuList() {
      const { data: res } = await this.$axios.get('/menu/getMenuList.do')
      if (!res.flag) return this.$message.error(res.message)
      // 获取当前激活路径
      const activePath = window.sessionStorage.getItem('activePath')
      // 循环判断激活路径对应的路径名称
      res.data.forEach(value => {
        value.menuItem.forEach(item => {
          if (item.path === activePath) {
            this.menuTitle.item = item.title
            this.menuTitle.main = value.title
          }
        })
      })
    },
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$axios.post('/user/getUserList.do', this.queryInfo)
      if (res === null) return this.$message.error('获取用户列表失败')
      this.total = res.total
      this.userList = res.rows
    },
    // 更新用户账号状态
    async updateState(row) {
      // 向后台发起请求, 修改用户的激活状态
      const { data: res } = await this.$axios.put(`/user/changeState.do?id=${row.id}`)
      if (res.flag) return this.$message.success(res.message)

      row.state = !row.state
      this.$message.error(res.message)
    },
    // 处理当前页发生变化
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getUserList()
    },
    // 处理每页条数发生变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 判断用户名是否唯一
    async findUsernameExist() {
      const { data: res } = await this.$axios.get(`/user/exist.do?username=${this.addForm.username}`)
      return res.flag
    },
    // 添加用户对话框关闭时
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const flag = await this.findUsernameExist()
        if (flag) return this.$message.warning('当前用户名已经存在, 请更换')

        const { data: res } = await this.$axios.post('/user/add.do', this.addForm)
        if (!res.flag) return this.$message.error(res.message)

        this.addDialogVisible = false
        this.getUserList()
        this.$message.success(res.message)
      })
    },
    // 展示编辑用户信息对话框
    async showEditDialog(id) {
      const { data: res } = await this.$axios.get(`/user/getUserById.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)
      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false

        const { data: res } = await this.$axios.put('/user/edit.do', this.editForm)
        if (!res.flag) return this.$message.error(res.message)

        this.editDialogVisible = false
        this.getUserList()
        this.$message.success(res.message)
      })
    },
    // 修改用户信息对话框关闭时
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户
    async deleteUser(id) {
      // 防止用户误操作
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)

      if (result !== 'confirm') return this.$message.info('已经取消删除')

      const { data: res } = await this.$axios.delete(`/user/delete.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)

      this.$message.success(res.message)
      this.getUserList()
    },
    // 分配角色
    async showDisDialog(row) {
      this.usr = row
      this.role = row.role

      const { data: res } = await this.$axios.get(`/user/getUserById.do?id=${row.id}`)
      if (!res.flag) return this.$message.error(res.message)
      this.editForm = res.data

      const { data: rs } = await this.$axios.get('/role/findAll.do')
      if (!rs.flag) return this.$message.error(rs.flag)
      this.rolesList = rs.data

      this.disDialogVisible = true
    },
    // 选择发生变化
    selected(row) {
      this.roleId = row.id
    },
    // 分配角色
    async distribution() {
      if (this.roleId === '') return this.$message.warning('请选择角色')
      const { data: res } = await this.$axios.put(`/user/changeUserRole.do?userId=${this.editForm.id}&roleId=` + this.roleId.id)
      if (!res.flag) return this.$message.error(res.message)

      this.$message.success(res.message)
      this.disDialogVisible = false
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin-left: 100px;
}

.tag {
  margin-right: 150px;
}
</style>
